<template>
  <div class="merchant-management">
    <h2>商家管理</h2>
    <div class="controls">
      <button class="add-btn" @click="showAddModal = true">新增商家</button>
      <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索商家名称..."
          class="search-input"
          @keyup.enter="fetchMerchants"
      />
      <select v-model="serviceFilter" class="service-filter" @change="fetchMerchants">
        <option value="">所有服务类型</option>
        <option value="洗衣">洗衣</option>
        <option value="租赁">租赁</option>
        <option value="保养">保养</option>
        <option value="修护">修护</option>
      </select>
      <button class="reset-btn" @click="resetFilters">重置</button>
    </div>

    <!-- 商家列表 -->
    <table class="merchant-table">
      <thead>
      <tr>
        <th>ID</th>
        <th>商家名称</th>
        <th>地址</th>
        <th>联系电话</th>
        <th>服务类型</th>
        <th>头像</th>
        <th>海报</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="merchant in paginatedMerchants" :key="merchant.merchantId" @click="showMerchantDetail(merchant.merchantId)">
        <td>{{ merchant.merchantId }}</td>
        <td>{{ merchant.name }}</td>
        <td>{{ merchant.address }}</td>
        <td>{{ merchant.contactNumber }}</td>
        <td>{{ merchant.services || '未设置' }}</td>
        <td>
          <img v-if="merchant.avatarUrl" :src="merchant.avatarUrl" alt="商家头像" class="thumbnail" @error="logImageError" />
          <span v-else>无头像</span>
        </td>
        <td>
          <img v-if="merchant.poster" :src="merchant.poster" alt="商家海报" class="thumbnail" />
          <span v-else>无海报</span>
        </td>
        <td @click.stop>
          <button class="edit-btn" @click="editMerchant(merchant)">编辑</button>
          <button class="delete-btn" @click="confirmDelete(merchant.merchantId)">删除</button>
          <button class="review-btn" @click="showReviews(merchant.merchantId)">查看评价</button>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 分页控件 -->
    <div class="pagination">
      <button :disabled="currentPage === 1" @click="currentPage--">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button :disabled="currentPage === totalPages" @click="currentPage++">下一页</button>
    </div>

    <!-- 新增/编辑商家模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal">
      <div class="modal-content">
        <h3>{{ showAddModal ? '新增商家' : '编辑商家' }}</h3>
        <form @submit.prevent="saveMerchant">
          <div class="form-group">
            <label>商家名称:</label>
            <input v-model="merchantForm.name" required />
          </div>
          <div class="form-group">
            <label>地址:</label>
            <input
                v-model="merchantForm.address"
                required
                @input="searchAddress"
                id="addressInput"
            />
            <MapContainer
                ref="editMap"
                style="width: 100%; height: 200px; margin-top: 10px;"
                :center="[merchantForm.longitude || 116.397428, merchantForm.latitude || 39.90923]"
                @update-position="updatePosition"
                @location-fetched="locationFetched"
            />
            <button type="button" @click="getCurrentLocation" class="location-btn">获取当前位置</button>
          </div>
          <div class="form-group">
            <label>联系电话:</label>
            <input v-model="merchantForm.contactNumber" required pattern="^\d{7,15}$" title="请输入7-15位数字的电话号码" />
          </div>
          <div class="form-group" v-if="showAddModal">
            <label>密码:</label>
            <input type="password" v-model="merchantForm.password" required placeholder="请输入密码" />
          </div>
          <div class="form-group">
            <label>服务类型 (多选):</label>
            <div class="checkbox-group">
              <label><input type="checkbox" value="洗衣" v-model="merchantForm.services" /> 洗衣</label>
              <label><input type="checkbox" value="租赁" v-model="merchantForm.services" /> 租赁</label>
              <label><input type="checkbox" value="保养" v-model="merchantForm.services" /> 保养</label>
              <label><input type="checkbox" value="修护" v-model="merchantForm.services" /> 修护</label>
            </div>
          </div>
          <div class="form-group">
            <label>纬度:</label>
            <input type="number" step="0.000001" v-model="merchantForm.latitude" required min="-90" max="90" />
          </div>
          <div class="form-group">
            <label>经度:</label>
            <input type="number" step="0.000001" v-model="merchantForm.longitude" required min="-180" max="180" />
          </div>
          <div class="form-group">
            <label>头像:</label>
            <input type="file" ref="avatarInput" @change="handleAvatarUpload" accept="image/*" />
            <img v-if="merchantForm.avatarUrl" :src="merchantForm.avatarUrl" alt="预览" class="preview-img" />
          </div>
          <div class="form-group">
            <label>海报:</label>
            <input type="file" ref="posterInput" @change="handlePosterUpload" accept="image/*" />
            <img v-if="merchantForm.poster" :src="merchantForm.poster" alt="预览" class="preview-img" />
          </div>
          <div class="form-actions">
            <button type="submit" class="save-btn">保存</button>
            <button type="button" class="cancel-btn" @click="closeModal">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 商家详情模态框 -->
    <div v-if="showDetailModal" class="modal">
      <div class="modal-content detail-modal">
        <h3>商家详情</h3>
        <div v-if="selectedMerchant">
          <p><strong>ID:</strong> {{ selectedMerchant.merchantId }}</p>
          <p><strong>名称:</strong> {{ selectedMerchant.name }}</p>
          <p><strong>地址:</strong> {{ selectedMerchant.address }}</p>
          <p><strong>联系电话:</strong> {{ selectedMerchant.contactNumber }}</p>
          <p><strong>服务类型:</strong> {{ selectedMerchant.services || '未设置' }}</p>
          <p><strong>纬度:</strong> {{ selectedMerchant.latitude }}</p>
          <p><strong>经度:</strong> {{ selectedMerchant.longitude }}</p>
          <p><strong>距离:</strong> {{ selectedMerchant.distance }} 千米</p>
          <p><strong>位置:</strong></p>
          <MapContainer
              style="width: 100%; height: 300px; margin-top: 10px;"
              :center="[selectedMerchant.longitude, selectedMerchant.latitude]"
              :zoom="15"
          />
          <p><strong>头像:</strong></p>
          <img v-if="selectedMerchant.avatarUrl" :src="selectedMerchant.avatarUrl" alt="头像" class="detail-img" />
          <span v-else>无头像</span>
          <p><strong>海报:</strong></p>
          <img v-if="selectedMerchant.poster" :src="merchant.poster" alt="海报" class="detail-img" />
          <span v-else>无海报</span>
        </div>
        <div class="form-actions">
          <button class="cancel-btn" @click="showDetailModal = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 查看商家评价模态框 -->
    <div v-if="showReviewModal" class="modal">
      <div class="modal-content review-modal">
        <h3>商家评价</h3>
        <div v-if="reviews.length > 0">
          <table class="review-table">
            <thead>
            <tr>
              <th>评价ID</th>
              <th>订单ID</th>
              <th>用户ID</th>
              <th>评分</th>
              <th>评论</th>
              <th>创建时间</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="review in reviews" :key="review.reviewId">
              <td>{{ review.reviewId }}</td>
              <td>{{ review.orderId }}</td>
              <td>{{ review.userId }}</td>
              <td>{{ review.rating }}</td>
              <td>{{ review.comment || '无评论' }}</td>
              <td>{{ formatDate(review.createdAt) }}</td>
            </tr>
            </tbody>
          </table>
        </div>
        <div v-else>
          <p>暂无评价</p>
        </div>
        <div class="form-actions">
          <button class="cancel-btn" @click="showReviewModal = false">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import debounce from 'lodash/debounce';
import MapContainer from '../components/MapContainer.vue';

export default {
  components: {
    MapContainer,
  },
  data() {
    return {
      merchants: [],
      searchQuery: '',
      serviceFilter: '',
      showAddModal: false,
      showEditModal: false,
      showDetailModal: false,
      showReviewModal: false,
      selectedMerchant: null,
      reviews: [],
      merchantForm: {
        merchantId: null,
        name: '',
        address: '',
        contactNumber: '',
        services: [],
        latitude: null,
        longitude: null,
        avatarUrl: '',
        poster: '',
        password: '',
      },
      avatarFile: null,
      posterFile: null,
      currentPage: 1,
      itemsPerPage: 5,
    };
  },
  computed: {
    adminInfo() {
      return this.$store.state.adminInfo || { username: '管理员', role: '', adminId: null };
    },
    isSuperAdmin() {
      return this.adminInfo.role === 'super';
    },
    filteredMerchants() {
      let filtered = this.merchants;
      if (this.searchQuery) {
        filtered = filtered.filter((merchant) =>
            merchant.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      if (this.serviceFilter) {
        filtered = filtered.filter((merchant) =>
            merchant.services && merchant.services.includes(this.serviceFilter)
        );
      }
      return filtered;
    },
    totalPages() {
      return Math.ceil(this.filteredMerchants.length / this.itemsPerPage);
    },
    paginatedMerchants() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredMerchants.slice(start, end);
    },
  },
  watch: {
    currentPage() {
      if (this.currentPage < 1) this.currentPage = 1;
      if (this.currentPage > this.totalPages) this.currentPage = this.totalPages;
    },
  },
  created() {
    this.fetchMerchants();
  },
  methods: {
    async fetchMerchants() {
      try {
        let response;
        if (this.isSuperAdmin) {
          response = await axios.get('/api/merchant/all', {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          });
        } else {
          response = await axios.get(`/api/merchant/by-admin/${this.adminInfo.adminId}`, {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          });
        }
        this.merchants = response.data;
        console.log('Fetched merchants:', this.merchants);
      } catch (error) {
        console.error('获取商家列表失败:', error);
        const message = error.response?.data?.message || '请稍后重试';
        alert('加载商家数据失败: ' + message);
      }
    },
    resetFilters() {
      this.searchQuery = '';
      this.serviceFilter = '';
      this.currentPage = 1;
      this.fetchMerchants();
    },
    editMerchant(merchant) {
      this.merchantForm = {
        merchantId: merchant.merchantId,
        name: merchant.name,
        address: merchant.address || '',
        contactNumber: merchant.contactNumber,
        services: merchant.services ? merchant.services.split(',') : [],
        latitude: merchant.latitude,
        longitude: merchant.longitude,
        avatarUrl: merchant.avatarUrl || '',
        poster: merchant.poster || '',
      };
      this.showEditModal = true;
    },
    closeModal() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.resetForm();
    },
    resetForm() {
      this.merchantForm = {
        merchantId: null,
        name: '',
        address: '',
        contactNumber: '',
        services: [],
        latitude: null,
        longitude: null,
        avatarUrl: '',
        poster: '',
        password: '',
      };
      this.avatarFile = null;
      this.posterFile = null;
      this.$refs.avatarInput.value = '';
      this.$refs.posterInput.value = '';
    },
    handleAvatarUpload(event) {
      this.avatarFile = event.target.files[0];
      if (this.avatarFile) {
        this.merchantForm.avatarUrl = URL.createObjectURL(this.avatarFile);
      }
    },
    handlePosterUpload(event) {
      this.posterFile = event.target.files[0];
      if (this.posterFile) {
        this.merchantForm.poster = URL.createObjectURL(this.posterFile);
      }
    },
    async saveMerchant() {
      if (!this.merchantForm.name || !this.merchantForm.address || !this.merchantForm.contactNumber) {
        alert('请填写所有必填字段');
        return;
      }
      if (this.merchantForm.latitude < -90 || this.merchantForm.latitude > 90 ||
          this.merchantForm.longitude < -180 || this.merchantForm.longitude > 180) {
        alert('纬度范围为-90到90，经度范围为-180到180');
        return;
      }

      const formData = new FormData();
      const merchantData = {
        merchantId: this.merchantForm.merchantId,
        name: this.merchantForm.name,
        address: this.merchantForm.address,
        contactNumber: this.merchantForm.contactNumber,
        services: this.merchantForm.services.join(','),
        latitude: this.merchantForm.latitude,
        longitude: this.merchantForm.longitude,
        avatarUrl: this.merchantForm.avatarUrl && !this.avatarFile ? this.merchantForm.avatarUrl : null,
        poster: this.merchantForm.poster && !this.posterFile ? this.merchantForm.poster : null,
        adminId: this.isSuperAdmin ? null : this.adminInfo.adminId,
      };
      if (this.showAddModal) {
        merchantData.password = this.merchantForm.password;
      }
      formData.append('merchantManagementDTO', new Blob([JSON.stringify(merchantData)], {type: 'application/json'}));
      if (this.avatarFile) formData.append('avatar', this.avatarFile);
      if (this.posterFile) formData.append('poster', this.posterFile);

      try {
        let response;
        if (this.showAddModal) {
          response = await axios.post('/api/merchant/add', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              Authorization: `Bearer ${sessionStorage.getItem('token')}`,
            },
          });
        } else {
          response = await axios.put(`/api/merchant/update/${this.merchantForm.merchantId}`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              Authorization: `Bearer ${sessionStorage.getItem('token')}`,
            },
          });
        }
        if (response.data.success) {
          alert(this.showAddModal ? '商家添加成功' : '商家更新成功');
          this.closeModal();
          this.fetchMerchants();
        } else {
          alert('操作失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('保存商家失败:', error);
        const message = error.response?.data?.message || '请检查输入或稍后重试';
        alert('保存失败: ' + message);
      }
    },
    confirmDelete(merchantId) {
      if (confirm('确定要删除此商家吗？')) {
        this.deleteMerchant(merchantId);
      }
    },
    async deleteMerchant(merchantId) {
      try {
        const response = await axios.delete(`/api/merchant/delete/${merchantId}`, {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
        });
        if (response.data.success) {
          alert('商家删除成功');
          this.fetchMerchants();
        } else {
          alert('删除失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('删除商家失败:', error);
        const message = error.response?.data?.message || '请稍后重试';
        alert('删除失败: ' + message);
      }
    },
    async showMerchantDetail(merchantId) {
      try {
        const response = await axios.get(`/api/merchant/detail/${merchantId}`, {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          params: { latitude: 39.9042, longitude: 116.4074 },
        });
        if (response.data.merchant) {
          this.selectedMerchant = response.data.merchant;
          this.showDetailModal = true;
        } else {
          alert('获取商家详情失败: ' + (response.data.error || '未知错误'));
        }
      } catch (error) {
        console.error('获取商家详情失败:', error);
        const message = error.response?.data?.message || '请稍后重试';
        alert('加载商家详情失败: ' + message);
      }
    },
    async showReviews(merchantId) {
      try {
        const response = await axios.get(`/api/reviews/byMerchantId/${merchantId}`, {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
        });
        this.reviews = response.data;
        this.showReviewModal = true;
      } catch (error) {
        console.error('获取商家评价失败:', error);
        const message = error.response?.data?.message || '请稍后重试';
        alert('加载评价失败: ' + message);
      }
    },
    formatDate(date) {
      return new Date(date).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
    },
    updatePosition({ lng, lat }) {
      this.merchantForm.longitude = lng;
      this.merchantForm.latitude = lat;
      this.reverseGeocode([lng, lat]);
    },
    locationFetched(lnglat) {
      this.merchantForm.longitude = lnglat[0];
      this.merchantForm.latitude = lnglat[1];
      this.reverseGeocode(lnglat);
    },
    getCurrentLocation() {
      if (this.$refs.editMap) {
        this.$refs.editMap.getCurrentLocation();
      }
    },
    searchAddress: debounce(function() {
      if (!this.merchantForm.address || !this.$refs.editMap) return;
      this.$refs.editMap.searchAddress(this.merchantForm.address);
    }, 300),
    reverseGeocode(lnglat) {
      if (!this.$refs.editMap) return;
      this.$refs.editMap.getAddress(lnglat, (address) => {
        this.merchantForm.address = address;
      });
    },
    logImageError(event) {
      console.error('头像加载失败:', event.target.src);
    },
  },
};
</script>

<style scoped>
.merchant-management {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 10px;
}

.add-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.add-btn:hover {
  background-color: #0056b3;
}

.search-input {
  padding: 10px;
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.service-filter {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.reset-btn {
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.reset-btn:hover {
  background-color: #5a6268;
}

.merchant-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  cursor: pointer;
}

.merchant-table th,
.merchant-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.merchant-table th {
  background-color: #f8f9fa;
  color: #333;
}

.merchant-table tr:hover {
  background-color: #f8f9fa;
}

.thumbnail {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.edit-btn,
.delete-btn,
.review-btn {
  padding: 6px 12px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #28a745;
  color: white;
}

.edit-btn:hover {
  background-color: #218838;
}

.delete-btn {
  background-color: #dc3545;
  color: white;
}

.delete-btn:hover {
  background-color: #c82333;
}

.review-btn {
  background-color: cornflowerblue;
  color: white;
}

.review-btn:hover {
  background-color: #5a32a3;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.pagination button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.pagination button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.pagination button:hover:not(:disabled) {
  background-color: #0056b3;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 12px;
  width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.detail-modal {
  width: 600px;
}

.review-modal {
  width: 700px;
}

.review-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.review-table th,
.review-table td {
  padding: 10px;
  border-bottom: 1px solid #eee;
  text-align: left;
}

.review-table th {
  background-color: #f8f9fa;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group input[type="password"] {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.checkbox-group {
  display: flex;
  gap: 15px;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.preview-img,
.detail-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-top: 10px;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.save-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #0056b3;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #5a6268;
}

.location-btn {
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.location-btn:hover {
  background-color: #218838;
}
</style>